﻿using MebAppMarketplace.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MebAppMarketplace.Biz
{
    public class BaseService : IDisposable
    {
        public DbContext Db { get; set; }

        internal BaseService(DbContext db)
        {
            this.Db = db;
        }

        /// <summary>
        /// 转换为另一种服务并共享数据库上下文
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public BaseService<T> AsService<T>() where T : BaseModel
        {
            return new BaseService<T>(Db);
        }

        public void Dispose()
        {
            Db.Dispose();
        }
    }

    public class BaseService<T> : BaseService where T : BaseModel
    {
        private DbSet<T> _dbset;
        public BaseService(DbContext db) : base(db)
        {

        }
        public DbSet<T> DbSet
        {
            get
            {
                return _dbset ?? (_dbset = Db.Set<T>());
            }
        }
    }
}
